from qiniu import Auth, put_file, etag, put_data, BucketManager, build_batch_delete
import qiniu.config

# 需要填写你的 Access Key 和 Secret Key


access_key = 'XXDk--8ZsKS_ioG7o7zuT_FiX2FQ6N8ptML-CsUo'
secret_key = 'GLLl6GQXa6U7Ou2-BiPOo2ned2liJ5IGRC9pQ5Br'
# 构建鉴权对象
q = Auth(access_key, secret_key)

# 要上传的空间
bucket_name = 'flask-user1'
bucket = BucketManager(q)


def video_upload(video_data, key):
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)

    # 二进制传输文件
    ret, info = put_file(token, key, video_data)
    print(ret, info)
    if info.status_code == 200:
        return ret.get("key")
    else:
        return None


def image_upload(image_data, key):
    # 上传后保存的文件名

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)

    # 二进制传输文件
    ret, info = put_data(token, key, image_data)
    print(ret, info)
    if info.status_code == 200:
        return ret.get("key")
    else:
        return None

    # assert ret['key'] == key
    # assert ret['hash'] == etag(localfile)


def list_image():
    # 前缀
    prefix = "test/"
    # 列举条目
    limit = 10
    # 列举出除'/'的所有文件以及以'/'为分隔的所有前缀
    delimiter = None
    # 标记
    marker = None
    ret, eof, info = bucket.list(bucket_name, prefix, marker, limit, delimiter)
    print(ret)
    # print(ret["items"])
    for res in ret["items"]:
        print(res)
        # if res.get("key") == :
    #         print(res)


def delete_image():
    key = ['test/25.jpeg']
    # 删除bucket_name 中的文件 key
    ops = build_batch_delete(bucket_name, key)
    ret, info = bucket.batch(ops)
    print(info)


def image_upload_test():
    # 上传后保存的文件名
    key = '/test/my-python-logo.png'
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # 要上传文件的本地路径
    localfile = 'E:\\壁纸\\1.jpeg'
    ret, info = put_file(token, key, localfile, version='v2')
    print(info)


if __name__ == '__main__':
    # image_upload_test()
    list_image()
    delete_image()
    # with open('E:\\壁纸\\1.jpeg', "rb") as f:
    #     print(image_upload(f.read(),"test/"+"1.jpg"))
